<template>
  <a-config-provider :locale="locale">
    <div class="form-designer-container-9136076486841527">
      <k-header v-if="showHead" :title="title" />
      <!-- 操作区域 start -->
      <operatingArea
        v-if="toolbarsTop"
        :showToolbarsText="showToolbarsText"
        :toolbars="toolbars"
        @handleSave="handleSave"
        @handlePreview="handlePreview"
        @handleOpenImportJsonModal="handleOpenImportJsonModal"
        @handleOpenCodeModal="handleOpenCodeModal"
        @handleOpenJsonModal="handleOpenJsonModal"
        @handleReset="handleReset"
        @handleClose="handleClose"
      >
        <template slot="left-action">
          <slot name="left-action"></slot>
        </template>
        <template slot="right-action">
          <slot name="right-action"></slot>
        </template>
      </operatingArea>
      <!-- 操作区域 end -->
      <div
        class="content"
        :class="{
          'show-head': showHead,
          'toolbars-top': toolbarsTop,
          'show-head-and-toolbars-top': toolbarsTop && showHead
        }"
      >
        <!-- 左侧控件区域 start -->
        <aside class="left">
          <a-collapse
            @change="collapseChange"
            :defaultActiveKey="collapseDefaultActiveKey"
          >
            <!-- 基础控件 start -->
            <a-collapse-panel
              v-if="basicsArray.length > 0"
              header="基础组件"
              key="1"
            >
              <collapseItem
                :list="basicsArray"
                @generateKey="generateKey"
                @handleListPush="handleListPush"
                @start="handleStart"
              />
            </a-collapse-panel>
            <!-- 基础控件 end -->
            <!-- 自定义控件 start -->
            <a-collapse-panel
              v-if="customComponents.length > 0"
              header="宏组件"
              key="3"
            >
              <collapseItem
                :list="customComponents"
                @generateKey="generateKey"
                @handleListPush="handleListPush"
                @start="handleStart"
              />
            </a-collapse-panel>
            <!-- 自定义控件 end -->
            <!-- 布局控件 start -->
            <a-collapse-panel
              v-if="layoutArray.length > 0"
              header="函数组件"
              key="4"
            >
              <collapseItem
                :list="layoutArray"
                @generateKey="generateKey"
                @handleListPush="handleListPush"
                @start="handleStart"
              />
            </a-collapse-panel>
            <!-- 布局控件 end -->
          </a-collapse>
        </aside>
        <!-- 左侧控件区域 end -->
        <!-- 中间面板区域 start -->
        <section>
          <!-- 操作区域 start -->
          <canvas
            id="myCanvas"
            width="1000"
            height="1000"
            style="position:absolute"
          >
            <p>您的系统不支持此程序!</p>
          </canvas>
          <div id="wrap" style="display:none;">
            <el-link icon="el-icon-delete" @click="deleteSelectObj">删除</el-link>
          </div>
        </section>
        <!-- 中间面板区域 end -->
        <!-- 右侧控件属性区域 start -->
        <aside class="right">
          <!--<formProperties
            :config="data.config"
            :previewOptions="previewOptions"
          />
          <formItemProperties
            :class="{ 'show-properties': showPropertie }"
            class="form-item-properties"
            :selectItem="selectItem"
            :hideModel="hideModel"
            @handleHide="showPropertie = false"
          /> -->
          <controlproperties :controlProperties="curCtrlProperties"  ref="childControlProperties" />
        </aside>
        <!-- 右侧控件属性区域 end -->
      </div>
      <!-- <k-footer /> -->
    </div>
  </a-config-provider>
</template>
<script>
import kHeader from "./module/header";
import operatingArea from "./module/operatingArea";
import collapseItem from "./module/collapseItem";
import controlproperties from "../ControlProperties/parent";
import request from "@/utils/request";

import zhCN from "ant-design-vue/lib/locale-provider/zh_CN";
import {
  basicsList,
  // highList,
  layoutList,
  customComponents
} from "./config/formItemsConfig";
import formItemProperties from "./module/formItemProperties";
import formProperties from "./module/formProperties";
import "../../exticon/iconfont.js";
import { Const } from "@/const";

let drop;
let canva;
let cansText;
let wrap;
let img1 = new Image();
export default {
  name: "KFormDesign",
  props: {
    title: {
      type: String,
      default: "代码模板设计器"
    },
    showHead: {
      type: Boolean,
      default: true
    },
    hideResetHint: {
      type: Boolean,
      default: false
    },
    toolbarsTop: {
      type: Boolean,
      default: false
    },
    toolbars: {
      type: Array,
      default: () => [
        "save",
        "preview",
        "importJson",
        "exportJson",
        "exportCode",
        "reset",
        "close"
      ]
    },
    showToolbarsText: {
      type: Boolean,
      default: false
    },
    fields: {
      type: Array,
      default: () => [
        "project",
        "template",
        "line",
        "tableloop",
        "fieldloop",
        "decide",
        "varinit",
        "tablecn",
        "tableen",
        "fieldcn",
        "fielden",
        "table2class",
        "table2file",
        "table2method",
        "field2prop",
        "field2method",
        "writefile",
        "date"
      ]
    },
    hideModel: {
      // 隐藏数据字段
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      locale: zhCN,
      customComponents,
      updateTime: 0,
      updateRecordTime: 0,
      showPropertie: false,
      startType: "",
      noModel: [
        "button",
        "divider",
        "card",
        "grid",
        "tabs",
        "table",
        "alert",
        "text",
        "html"
      ],
      data: {
        list: [],
        config: {
          layout: "horizontal",
          labelCol: { xs: 4, sm: 4, md: 4, lg: 4, xl: 4, xxl: 4 },
          wrapperCol: { xs: 18, sm: 18, md: 18, lg: 18, xl: 18, xxl: 18 },
          hideRequiredMark: false,
          customStyle: ""
        }
      },
      previewOptions: {
        width: 850
      },
      selectItem: {
        key: ""
      },
      project: {},
      listObj: new Array(),
      //图片缓存
      listImgCache: new Array(),
      //当前控件属性
      curCtrlProperties: [],
      //当前控件数值值
      propertiesData:[],
      //刚拖拽的控件属性
      newControlProperties:[],
      //当前选择对象
      curSelectObj:null,
      //是否按下鼠标
      bmousedown:false
    };
  },
  components: {
    kHeader,
    // kFooter,
    operatingArea,
    collapseItem,
    //kJsonModal,
    //kCodeModal,
    //importJsonModal,
    //previewModal,
    //kFormComponentPanel,
    formItemProperties,
    formProperties,
    controlproperties
  },
  computed: {
    basicsArray() {
      // 计算需要显示的基础字段
      return basicsList.filter(item => this.fields.includes(item.type));
    },
    layoutArray() {
      // 计算需要显示的布局字段
      return layoutList.filter(item => this.fields.includes(item.type));
    },
    collapseDefaultActiveKey() {
      // 计算当前展开的控件列表
      let defaultActiveKey = window.localStorage.getItem(
        "collapseDefaultActiveKey"
      );
      if (defaultActiveKey) {
        return defaultActiveKey.split(",");
      } else {
        return ["1"];
      }
    }
  },
  mounted() {
    wrap = document.getElementById("wrap");

    drop = document.getElementById("myCanvas");
    drop.ondragenter = this.dragenter;
    drop.ondragover = this.dragover;
    drop.ondragleave = this.dragleave;
    drop.ondrop = this.drop;
    canva = document.getElementById("myCanvas");
    canva.onclick = this.canvasclick;
    canva.onmousemove = this.mousemove;
    canva.onmousedown = this.mousedown;
    canva.onmouseup = this.mouseup;
    wrap.oncontextmenu=this.contenxtmenu;
    canva.oncontextmenu= this.contenxtmenu;

    wrap.onclick=this.hiddencontenxtmenu;
    // canva.onclick= this.hiddencontenxtmenu;

    cansText = canva.getContext("2d");
  },
  methods: {
    hiddencontenxtmenu(){
      wrap.style.display = "none";
    },
    contenxtmenu(ev){
      console.log(ev.clientX);

      console.log(ev.clientY);

      wrap.style.left = ev.clientX+"px";

      wrap.style.top = ev.clientY+"px";

      wrap.style.display = "block";

      ev.preventDefault();
    },
    generateKey(e, list, index) {
      console.log("e draggable:" + e.target.draggable);
      e.dataTransfer.setData("id", e.target.id);
      if (e.target.id == Const.projectId) {
        //如果工程对象已经创建，则禁止拖拽
        var isempty = JSON.stringify(this.project) == "{}";
        if (!isempty) {
          e.preventDefault();
          return;
        }
      }
      var dragobj = document.getElementById(e.target.id);
      e.dataTransfer.setData("offsetx", e.x - this.getLeft(dragobj));
      e.dataTransfer.setData("offsety", e.y - this.getTop(dragobj));
      // 生成key值
      const key = list[index].type + "_" + new Date().getTime();
      this.$set(list, index, {
        ...list[index],
        key,
        model: key
      });
      if (this.noModel.includes(list[index].type)) {
        // 删除不需要的model属性
        delete list[index].model;
      }
    },
    handleListPush(item) {
      // 双击控件按钮push到list
      // 生成key值
      if (!this.selectItem.key) {
        // 在没有选择表单时，将数据push到this.data.list
        const key = item.type + "_" + new Date().getTime();
        item = {
          ...item,
          key,
          model: key
        };
        if (this.noModel.includes(item.type)) {
          // 删除不需要的model属性
          delete item.model;
        }
        const itemString = JSON.stringify(item);
        const record = JSON.parse(itemString);
        // 删除icon及compoent属性
        delete record.icon;
        delete record.component;
        this.data.list.push(record);
        this.handleSetSelectItem(record);
        return false;
      }
      this.$refs.KFCP.handleCopy(false, item);
    },
    handleOpenJsonModal() {
      // 打开json预览模态框
      this.$refs.jsonModal.jsonData = this.data;
      this.$refs.jsonModal.visible = true;
    },
    handleOpenCodeModal() {
      // 打开代码预览模态框
      this.$refs.codeModal.jsonData = this.data;
      this.$refs.codeModal.visible = true;
    },
    handleOpenImportJsonModal() {
      // 打开json预览模态框
      this.$refs.importJsonModal.jsonData = this.data;
      this.$refs.importJsonModal.handleSetSelectItem = this.handleSetSelectItem;
      this.$refs.importJsonModal.visible = true;
    },
    handlePreview() {
      // 打开预览模态框
      //this.$refs.previewModal.jsonData = this.data;
      //this.$refs.previewModal.previewWidth = this.previewOptions.width;
      //this.$refs.previewModal.visible = true;
    },
    handleReset() {
      // 清空
      if (this.hideResetHint) {
        // 不显示提示直接清空
        this.resetData();
        return;
      }
      this.$confirm({
        title: "警告",
        content: "是否确认清空内容?",
        okText: "是",
        okType: "danger",
        cancelText: "否",
        onOk: () => {
          this.resetData();
        }
      });
    },
    resetData() {
      this.data = {
        list: [],
        config: {
          layout: "horizontal",
          labelCol: { xs: 4, sm: 4, md: 4, lg: 4, xl: 4, xxl: 4 },
          wrapperCol: { xs: 18, sm: 18, md: 18, lg: 18, xl: 18, xxl: 18 },
          hideRequiredMark: false,
          customStyle: ""
        }
      };
      this.handleSetSelectItem({ key: "" });
      this.$message.success("已清空");
    },
    handleSetSelectItem(record) {
      console.log("handleSetSelectItem");
      // 操作间隔不能低于100毫秒
      let newTime = new Date().getTime();
      if (newTime - this.updateTime < 100) {
        return false;
      }
      this.updateTime = newTime;
      // 设置selectItem的值
      this.selectItem = record;
      // 判断是否选中控件，如果选中则弹出属性面板，否则关闭属性面板
      if (record.key) {
        this.startType = record.type;
        this.showPropertie = true;
      } else {
        this.showPropertie = false;
      }
    },
    /**
     * @Author: kcz
     * @description: 遍历json结构，获取所有字段
     * @param {*}
     * @return {*} Array
     */
    getFieldSchema() {
      let fields = [];
      const traverse = array => {
        array.forEach(element => {
          if (element.type === "grid" || element.type === "tabs") {
            // 栅格布局
            element.columns.forEach(item => {
              traverse(item.list);
            });
          } else if (element.type === "card") {
            // 卡片布局
            traverse(element.list);
          } else if (element.type === "batch") {
            // 动态表格内复制
            traverse(element.list);
          } else if (element.type === "table") {
            // 表格布局
            element.trs.forEach(item => {
              item.tds.forEach(val => {
                traverse(val.list);
              });
            });
          } else {
            if (element.model) {
              fields.push(element);
            }
          }
        });
      };
      traverse(this.data.list);
      return fields;
    },
    handleSetData(data) {
      // 用于父组件赋值
      try {
        if (typeof data !== "object") {
          return false;
        } else {
          this.data = data;
          // 导入json数据后，需要清除已选择key
          this.handleSetSelectItem({ key: "" });
        }
        return true;
      } catch (error) {
        console.error(error);
        return false;
      }
    },
    collapseChange(val) {
      // 点击collapse时，保存当前collapse状态
      window.localStorage.setItem("collapseDefaultActiveKey", val);
    },
    handleStart(type, list) {
      console.log("handleStart,type:" + type + ",list:" + list);
      this.startType = type;
    },
    handleSave() {
      // 保存函数
      this.$emit("save", JSON.stringify(this.data));
    },
    getValue() {
      // 获取数据
      return this.data;
    },
    handleClose() {
      this.$emit("close");
    },
    getTop(e) {
      var offset = e.offsetTop;
      if (e.offsetParent != null) offset += this.getTop(e.offsetParent);
      return offset;
    },
    getLeft(e) {
      if (e != null) {
        var offset = e.offsetLeft;
        if (e.offsetParent != null) offset += this.getLeft(e.offsetParent);
        return offset;
      }
    },
    dragenter(e) {
      console.log("dragenter" + e);
      e.preventDefault();
    },
    drop(e) {
      // console.log("enter drop");
      // console.log("scrolltop:" + document.documentElement.scrollTop);
      var objId = e.dataTransfer.getData("id");
      var offsetX = e.dataTransfer.getData("offsetx");
      var offsetY = e.dataTransfer.getData("offsety");
      debugger;
      if (document.getElementById(objId) != null) {
        console.log("img:" + document.getElementById(objId).dataset.img);
        var x = e.clientX - offsetX;
        var y = e.clientY - offsetY;
        var rect = canva.getBoundingClientRect();
        var getBoundingClientRectTop = rect.top * (canva.height / rect.height);
        var getBoundingClientRectLeft = rect.left * (canva.width / rect.width);
        var realy =
          y - getBoundingClientRectTop - document.documentElement.scrollTop;
        var realx =
          x - getBoundingClientRectLeft - document.documentElement.scrollLeft;
        console.log("x=" + realx + ",y=" + realy);
        var that = this;
        //优先从缓存搜索
        // var tmpimg1 = this.findImgFromCache(objId);
        // if (tmpimg1 == null) {
          img1.src = document.getElementById(objId).dataset.img;
          img1.onload = function() {
            //ctx.drawImage(image, 0, 0);
            cansText.drawImage(img1, realx, realy, img1.width, img1.height);
            cansText.stroke();
            //创建对象
            that.createDragObject(objId, e, realx, realy, img1);
            //加入图片对象缓存
            that.addImgCache(objId, img1);
          };
        // } else {
        //   img1 = tmpimg1;
        //   cansText.drawImage(img1, realx, realy, img1.width, img1.height);
        //   cansText.stroke();
        //   //创建对象
        //   that.createDragObject(objId, e, realx, realy, img1);
        // }
      } else {
        //文本处理
        var text = e.dataTransfer.getData("text/plain");
        console.log("drag text:" + text);
      }
      e.preventDefault();
      e.stopPropagation();
    },
    dragover(e) {
      e.preventDefault();
      //  console.log('dragover'+e);
    },
    dragleave(e) {
      e.preventDefault();
      //console.log('dragleave'+e);
    },
    //创建对象
    async createDragObject(objId, event, realx, realy, img1) {
      var width = img1.width;
      var height = img1.height;
      var src = img1.src;
      var newObj;
      debugger;
      switch (objId) {
        //工程对象
        case Const.projectId:
          this.project = {
            type: objId,
            id: objId + "_" + new Date().getTime(),
            x: realx,
            y: realy,
            width: width,
            height: height,
            src: src,
            iselect: false,
            properties:null,
            propertiesData:null
          };
          this.listObj.push(this.project);
          newObj = this.project;
          break;
        //线对象
        case Const.lineId:
          //TODO 需要特殊处理
          var line = {
            type: objId,
            id: objId + "_" + new Date().getTime(),
            x: realx,
            y: realy,
            width: width,
            height: height,
            src: src,
            iselect: false,
            properties:null,
            propertiesData:null
          };
          newObj = line;
          this.listObj.push(line);
          break;
        //其他对象
        default:
          var template = {
            type: objId,
            id: objId + "_" + new Date().getTime(),
            x: realx,
            y: realy,
            width: width,
            height: height,
            src: src,
            iselect: false,
            properties:null,
            propertiesData:null

          };
          newObj = template;
          this.listObj.push(template);
      }
      debugger;
      if(newObj){
        //保存当前对象值
        if(this.curSelectObj!=null){
          console.log("childControlProperties.data:"+JSON.stringify(this.$refs.childControlProperties.getPropertiesValue()));
          this.curSelectObj.propertiesData = this.$refs.childControlProperties.getPropertiesValue();
        }
        //调用接口，查询属性定义
        await  this.getControlProperties(newObj.type);
        console.log('newControlProperties:'+this.newControlProperties);
        //放入属性
        newObj.properties=this.newControlProperties;
        //清空上一个选中对象
        this.clearPrevSelectObj();
        //画新的选中对象
        this.drawNewSelectObj(newObj);
        //展示新对象属性
        console.log('newObj.x='+newObj.x+'newObj.y='+newObj.y);
        if(newObj.propertiesData==null){
          newObj.propertiesData={};
        }
        newObj.propertiesData["x"] = newObj.x;
        newObj.propertiesData["y"] = newObj.y;
        this.$refs.childControlProperties.setPropertiesValue(newObj.propertiesData);
        this.curCtrlProperties = newObj.properties;
        console.log('this.curCtrlProperties:'+JSON.stringify(this.curCtrlProperties));
        this.propertiesData = newObj.propertiesData;

        //初始化x,y
        // this.propertiesData.x = realx;
        // this.propertiesData.y = realy;
        // console.log('this.propertiesData:'+this.propertiesData);

        this.curSelectObj = newObj;
      }
    },
    //画布单击事件
    canvasclick(event) {
      //标准的获取鼠标点击相对于canvas画布的坐标公式
      debugger;
      //console.log('event button:'+event.button);
      this.hiddencontenxtmenu();
      //TODO 保存当前对象属性值
      if(this.curSelectObj!=null){
        console.log("childControlProperties.data:"+JSON.stringify(this.$refs.childControlProperties.getPropertiesValue()));
        this.curSelectObj.propertiesData = this.$refs.childControlProperties.getPropertiesValue();
        //填充到对象属性
        // this.fillCtrlProperties(this.curSelectObj,this.curSelectObj.propertiesData);
      }
      var p = this.getEventPosition(event);
      var selectObj = this.getSelectObject(p.x, p.y);
      if (selectObj != null) {

        //清空上一个选中对象
        this.clearPrevSelectObj();
        //画新的选中对象
        this.drawNewSelectObj(selectObj);
        //展示新对象属性
        this.$refs.childControlProperties.setPropertiesValue(selectObj.propertiesData);
        this.curCtrlProperties = selectObj.properties;
        // this.propertiesData = selectObj.propertiesData;
        //填充到对象属性
        // this.fillCtrlProperties(selectObj,selectObj.propertiesData);
        console.log('selectObj.propertiesData:'+JSON.stringify(selectObj.propertiesData));
        this.curSelectObj = selectObj;
      }else{
        //清空上一个选中对象
        this.clearPrevSelectObj();
        this.curSelectObj = null;
        this.curCtrlProperties=[];
        this.propertiesData = null;
      }
      console.log("select obj:" + selectObj);
    },
    //获取选中对象
    getSelectObject(x, y) {
      for (var j = 0, len = this.listObj.length; j < len; j++) {
        var obj = this.listObj[j];
        if (
          x >= obj.x &&
          x <= obj.x + obj.width &&
          y >= obj.y &&
          y <= obj.y + obj.height
        ) {
          return obj;
        }
      }
      return null;
    },
    //获取事件位置
    getEventPosition(ev) {
      var x, y;
      if (ev.layerX || ev.layerX == 0) {
        x = ev.layerX;
        y = ev.layerY;
      } else if (ev.offsetX || ev.offsetX == 0) {
        // Opera
        x = ev.offsetX;
        y = ev.offsetY;
      }
      return { x: x, y: y };
    },
    //清空上一个选中对象
    clearPrevSelectObj() {
      for (var j = 0, len = this.listObj.length; j < len; j++) {
        var obj = this.listObj[j];
        if (obj.iselect) {
          //清空，重画
          obj.iselect = false;
          cansText.clearRect(
            obj.x - 2,
            obj.y - 2,
            obj.width + 3,
            obj.height + 3
          );
          var img = this.findImgFromCache(obj.type);
          if (img != null) {
            cansText.drawImage(img, obj.x, obj.y, obj.width, obj.height);
            cansText.stroke();
            return;
          }
        }
      }
    },
    //清空旧位置对象
    clearOldSelectObj() {
      for (var j = 0, len = this.listObj.length; j < len; j++) {
        var obj = this.listObj[j];
        if (obj.iselect) {
          //清空，重画
          obj.iselect = false;
          cansText.clearRect(
            obj.x - 2,
            obj.y - 2,
            obj.width + 3,
            obj.height + 3
          );
          return;
        }
      }
    },
    //画新选中对象
    drawNewSelectObj(selectObj) {
      var obj = selectObj;
      obj.iselect = true;
      //设置线条颜色，必须放在绘制之前
      cansText.strokeStyle = "#00ff00";
      // 线宽设置，必须放在绘制之前
      cansText.lineWidth = 1;
      cansText.strokeRect(obj.x - 1, obj.y - 1, obj.width + 1, obj.height + 1);
      var img = this.findImgFromCache(obj.type);
      if (img != null) {
        cansText.drawImage(img, obj.x, obj.y, obj.width, obj.height);
        cansText.stroke();
      }
    },
    //从图片缓存搜索图片
    findImgFromCache(objId) {
      for (var j = 0, len = this.listImgCache.length; j < len; j++) {
        var obj = this.listImgCache[j];
        if (obj.objId === objId) {
          console.log('found obj id:'+objId+' src');
          console.log(obj.img.src);
          return obj.img;
        }
      }
      return null;
    },
    //加入图片对象缓存
    addImgCache(objId, img1) {
      var newImg = new Image();
      newImg.src = img1.src;
      // var obj = { objId: objId, img: newImg };
      var that = this;
      newImg.onload = function() {
        debugger;
        var obj = new Object();
        obj["objId"] = objId;
        obj["img"] = newImg;
        that.listImgCache.push(obj);
      }
    },
    //获取控件属性定义
    async  getControlProperties(controlType){
      const that = this;
      await request({
        method: "GET",
        url: '/api/ControlProperties/listControlProperitesByType?controlType='+controlType,
      })
        .then(res => {
          if (res.data.status == "1") {
            that.newControlProperties = res.data.list;
            console.log("that.newControlProperties:"+that.newControlProperties);
          }else{
            alert(res.data.message);
          }
          console.log("res:"+res);
        })
        .catch(err => {
          console.log(err);
        });
    },
    //填充属性值到指定对象属性数值
    fillCtrlProperties(obj,propertiesData){
      // debugger;
      obj.properties.forEach(function(value, index) {
        // debugger;
        value.ctrlVal=propertiesData[value.model];
        console.log('value=', value, 'index=', index);
      })
    },
    //重画与指定对象相交的对象
    redrawIntersectOfSelectObj(selectObj) {
      for (var j = 0, len = this.listObj.length; j < len; j++) {
        var obj = this.listObj[j];
        if (this.checkIntersect(obj,selectObj)) {
          var img = this.findImgFromCache(obj.type);
          if (img != null) {
            cansText.drawImage(img, obj.x, obj.y, obj.width, obj.height);
            cansText.stroke();
          }
        }
      }
    },
    //判断两个对象相交
    checkIntersect(objectA,objectB){
      var rectA={};
      var rectB={};
      //构造A框
      rectA.left = objectA.x;
      rectA.top = objectA.y;
      rectA.right = rectA.left+objectA.width;
      rectA.bottom = rectA.top+objectA.height;
      //构造B框
      rectB.left = objectB.x;
      rectB.top = objectB.y;
      rectB.right = rectB.left+objectB.width;
      rectB.bottom = rectB.top+objectB.height;
      var nonIntersect =
        (rectB.right < rectA.left )||
        (rectB.left > rectA.right )||
        (rectB.bottom < rectA.top )||
        (rectB.top > rectA.bottom);
      return !nonIntersect;
    },
    //画布移动事件
    mousemove(e){
      // console.log('e.button:'+e.button);
      if(this.bmousedown && this.curSelectObj ){
        debugger;
        console.log('mousedown and leftclick event:'+e);
        var x = e.clientX ;
        var y = e.clientY ;
        var rect = canva.getBoundingClientRect();
        var getBoundingClientRectTop = rect.top * (canva.height / rect.height);
        var getBoundingClientRectLeft = rect.left * (canva.width / rect.width);
        var realy =
          y - getBoundingClientRectTop;// + document.documentElement.scrollTop;
        var realx =
          x - getBoundingClientRectLeft;// + document.documentElement.scrollLeft;

        this.curSelectObj.propertiesData["x"] = realx;
        this.curSelectObj.propertiesData["y"] = realy;
        this.$refs.childControlProperties.setPropertiesValue(this.curSelectObj.propertiesData);
        // this.curCtrlProperties = newObj.properties;
        // console.log('this.curCtrlProperties:'+JSON.stringify(this.curCtrlProperties));
        this.propertiesData = this.curSelectObj.propertiesData;
        //清空上一个选中对象
        var tempObj = this.curSelectObj;
        this.clearOldSelectObj();
        this.curSelectObj = tempObj;
        this.curSelectObj.x = realx;
        this.curSelectObj.y = realy;
        //画新的选中对象
        this.drawNewSelectObj(this.curSelectObj);
        //重画与当前选中对象相交的对象
        this.redrawIntersectOfSelectObj(this.curSelectObj);
      }
    },
    //鼠标按下
    mousedown(e){
      //按左键是0，按右键是2
      if(e.button ==0) {
        this.bmousedown = true;
      }
    },
    //鼠标释放
    mouseup(e){
      debugger;

      this.bmousedown = false;
    },
    //按键事件
    deleteSelectObj(){

      if( this.curSelectObj){
        // e.preventDefault();
        //提示是否删除
        this.$confirm("是否删除选中对象?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          //临时保存当前对象
          var tempObj = this.curSelectObj;
          //清空对象画的位置
          this.clearOldSelectObj();
          //从数组删除
          this.removeObject(this.curSelectObj);
          this.curSelectObj = null;
          this.curCtrlProperties=[];
          this.propertiesData = null;
          //重画与对象相交的对象
          this.redrawIntersectOfSelectObj(tempObj);
          //如果当前工程对象等于当前对象，则清空工程对象
          if(this.project=== tempObj){
            this.project = {};
          }
        });
      }
    },
    //删除对象
    removeObject(obj) {
      for (var j = 0, len = this.listObj.length; j < len; j++) {
        var cmpObj = this.listObj[j];
        if (obj.id === cmpObj.id) {
          this.listObj.splice(j,1);
          return;
        }
      }
    }
  }
};
</script>
<style>
.icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}
#wrap{
  height: 100px;
  width:100px;
  background:#f8fafc;
  position: absolute;
}

</style>
